package cn.kxx.controller;

import cn.kxx.config.ValidateCodeUtils;
import cn.kxx.constant.MessageConstant;
import cn.kxx.constant.RedisConstant;
import cn.kxx.entity.Result;
import cn.kxx.exception.BusinessException;
import cn.kxx.utils.SMSUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.TimeUnit;

@Api("验证码接口")
@RestController
@RequestMapping("validateCode")
public class ValidateCodeController {
    @Autowired
    private RedisTemplate redisTemplate;
    @ApiOperation("发送验证码")
    @GetMapping("sendCode/{telephone}")
    public Result sendCode(@PathVariable("telephone")String telephone){
//        生成验证码
        try {
            String code = String.valueOf(ValidateCodeUtils.generateValidateCode(4));
            System.out.println("发送的验证码是"+code);
//        发送验证码
            SMSUtils.sendShortMessage(null,telephone,code);
//        将发送的验证码放到redis缓存内 失效时间为5分钟
            redisTemplate.opsForValue().set(RedisConstant.SENDTYPE_ORDER+":"+telephone,code,60*5,TimeUnit.SECONDS);
        } catch (Exception e) {
            throw new BusinessException("发送验证码失败");
        }
        return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);

    }
}
